﻿using Furion.RemoteRequest.Extensions;
using Spire.Additions.Qt;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Text;

namespace apitest.Application
{

    [DynamicApiController]
    public class Test2Service  
    {
        ISqlSugarClient _db;
        IHttpClientFactory _httpClientFactory;
       
        string Token = "YEWURth7cohTaLAjg3yc41cfLurPAe2Q1F33vseulYFmTl51kLxsCbt7tgDqPDA52YMHI_ZSAZj4KXDKtXgDwV5jmJf-BeLMd17nbMSXxs3BZmsDVWDrJvQePUfiVqN0PxU4hGQLotrUdzvvcgNFsaNCcaD9-7BRY1yrGMtjBTwjABUkUMuPPd6Pw3Aq8oKfjv5QpSa2JGlZerImrdN49w";
        public Test2Service(ISqlSugarClient db, IHttpClientFactory httpClientFactory )
        {
            _db = db;
            _httpClientFactory = httpClientFactory;
            
        }
        public async Task<dynamic> T1()
        {
            //假期 先不统计半天假日

            List<string> holidays = new List<string>() { "2023-01-02", "2023-1-3", "2023-1-5", "2023-1-6", "2023-1-10", "2023-01-11" };


            //下午2点开始
            var startDate = DateTime.Parse("2023-1-1 15:00:00");

            //耗时
            double useDay = 2.5;

            DateTime tartgentDate = startDate;
            ComputeDate(startDate, useDay, holidays, ref tartgentDate);

            return tartgentDate;
            Console.WriteLine($"预计结束日期为：{tartgentDate}");

            Console.ReadLine();
        }

        /// <summary>
        /// 计算 预计检测完毕时间
        /// </summary>
        /// <param name="currentDate">开始日期</param>
        /// <param name="useDay">用时</param>
        /// <param name="holidays">假期数组</param>
        /// <param name="tartgentDate">预计检测完毕时间</param>
        /// <returns></returns>
        private static void ComputeDate(DateTime currentDate, double useDay, List<string> holidays, ref DateTime tartgentDate)
        {
            if (useDay == 0)
            {
                return;
            }
            else if (useDay < 1)
            {
                /*
                 如果是同天，则直接返回
                 下一天， 则判断是否是假期
                 */
                tartgentDate = currentDate.AddDays(useDay);
                if (tartgentDate.Date == currentDate.Date) return;

                GetNoHoliday(holidays, ref tartgentDate);
                return;
            }
            else
            {
                // 判断下一天是否是假期
                tartgentDate = currentDate.AddDays(1);
                GetNoHoliday(holidays, ref tartgentDate);
                useDay--;
                ComputeDate(tartgentDate, useDay, holidays, ref tartgentDate);

                return;
            }
        }

        /// <summary>
        /// 检查是否是 假期，是的话，时间向后挪一天
        /// </summary>
        /// <param name="holidays"></param>
        /// <param name="tartgentDate"></param>
        private static void GetNoHoliday(List<string> holidays, ref DateTime tartgentDate)
        {
            if (holidays.Contains(tartgentDate.ToString("yyyy-M-d"))
                || holidays.Contains(tartgentDate.ToString("yyyy-MM-dd"))
                || holidays.Contains(tartgentDate.ToString("yyyy-MM-d"))
                || holidays.Contains(tartgentDate.ToString("yyyy-M-dd"))
                )
            {
                tartgentDate = tartgentDate.AddDays(1);
                GetNoHoliday(holidays, ref tartgentDate);
            }
        }

        public async Task<dynamic> T2()
        {
            var holiday = await _db.Queryable<Holiday>()
                .Select(o => o.Date.Date).ToListAsync();
            DateTime start = DateTime.Parse("2024-02-02 19:00:00");
            DateTime end = DateTime.Parse("2024-02-05 21:00:00");


            var startDate = start.Date;
            var endDate = end.Date;
            var ts = endDate - startDate;
            double total = 0;
            var totalDays = ts.Days;
            if (totalDays <= 1)
            {

                var d = startDate.AddDays(1);
                var min1 = (end - start).TotalMinutes;
                total += min1;
            }
            else
            {
                var computedDate = startDate.AddDays(1);

                while (computedDate < endDate)
                {
                    if (!holiday.Contains(computedDate))
                    {
                        total += 1440;
                    }
                    computedDate = computedDate.AddDays(1);
                }
                //单独计算开始和结束 
                if (!holiday.Contains(startDate))
                {
                    var d = startDate.AddDays(1);
                    var min1 = (startDate.AddDays(1) - start).TotalMinutes;
                    total += min1;
                }

                //单独计算开始和结束 
                if (!holiday.Contains(endDate))
                {
                    var min1 = (end - endDate).TotalMinutes;
                    total += min1;
                }
            }
            return total;
        }

        public async Task TestPdf()
        {
            var path = @"C:\Users\Lenovo\Desktop\img";
            var dirInfo = new DirectoryInfo(path);
            var files = dirInfo.GetFiles().ToList();
            var list = files.Select(o => o.FullName).Take(14).ToList();

            ConvertImagetoPDF(list);
        }


        public static void ConvertImagetoPDF(List<string> list)
        {
            PdfDocument pdfDoc = new PdfDocument();
            pdfDoc.Pages.Add();
            pdfDoc.Pages.RemoveAt(0);


            for (int i = 0; i < list.Count; i++)
            {
                //Image image = Image.FromFile(list[i]);
                PdfImage pdfImg = PdfImage.FromFile(list[i]);
                PdfPageBase page = pdfDoc.Pages.Add();
                float width = pdfImg.Width * 0.6f;
                float height = pdfImg.Height * 0.6f;
                float x = (page.Canvas.ClientSize.Width - width) / 2;

                page.Canvas.DrawImage(pdfImg, x, 0, width, height);
            }

            string PdfFilename = @"img\result123.pdf";
            pdfDoc.SaveToFile(PdfFilename);
            Process process = new Process();
            ProcessStartInfo processStartInfo = new ProcessStartInfo(PdfFilename);
            process.StartInfo = processStartInfo;
            process.StartInfo.UseShellExecute = true;
            process.Start();
            pdfDoc.Dispose();
        }

        public async Task   UrlToPdf()
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Create a PdfPageSettings object
            PdfPageSettings setting = new PdfPageSettings();

            //Save page size and margins through the object
            setting.Size = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            //Specific the URL path to convert
            String url = "https://v1.uviewui.com/guide/globalVariable.html";

            //Load HTML from a URL path using LoadFromHTML method
            //Thread thread = new Thread(async () =>
            //{
            //    var b = await url.GetAsByteArrayAsync();
            //    var d = await url.SetContentEncoding(encoding: Encoding.Unicode).GetAsStringAsync();
            //    var s = await url.GetAsStreamAsync();
            //    doc.LoadFromBytes(b);
            //});
            //thread.SetApartmentState(ApartmentState.STA);
            //thread.Start();
            //thread.Join();

            var b = await url.GetAsByteArrayAsync();
            //doc.LoadFromBytes(b);
            var s = await url.GetAsStreamAsync();
            doc.LoadFromStream(s.Stream);
            //Save the document to a PDF file
            doc.SaveToFile("UrlToPdf.pdf");
            doc.Close();
        }

        public void t11()
        {
            string url = "https://developer.work.weixin.qq.com/document/path/90256";

            //指定输出文件路径
            string fileName = "./Url转Pdf.pdf";

            //指定插件路径
            string pluginPath = "C:\\123\\plugins";

            //设置插件路径
            HtmlConverter.PluginPath = pluginPath;

            //将HTML网页转换为PDF
            HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
        }


        public static Image[] SplitImages(Image image, ImageFormat format)
        {
            Guid guid = image.FrameDimensionsList[0];
            FrameDimension dimension = new FrameDimension(guid);
            int pageCount = image.GetFrameCount(dimension);

            Image[] frames = new Image[pageCount];

            for (int i = 0; i < pageCount; i++)
            {
                using (MemoryStream buffer = new MemoryStream())
                {
                    image.SelectActiveFrame(dimension, i);
                    image.Save(buffer, format);
                    frames[i] = Image.FromStream(buffer);
                }
            }
            return frames;
        }

       


        public async Task<dynamic> SendMessage()
        {
            //var mess = Encoding.Default.GetString(sarr);
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={Token}";

            var body = new
            {
                touser = "ChenJia",
                toparty = "",
                totag = "消息提醒",
                msgtype = "text",
                agentid = 1000077,
                text = new
                {
                    content = "afdsfffffff"
                },
                safe = 0,
                enable_id_trans = 0,
                enable_duplicate_check = 0,
                duplicate_check_interval = 1800,
            };
            var response = await url.SetBody(body, "application/json").PostAsStringAsync();
            return response;
        }




        //using (var content = new MultipartFormDataContent())
        //{
        //    var filePath = Path.GetTempFileName();
        //    using (var fileStream = new FileStream(filePath,   FileMode.OpenOrCreate, FileAccess.Read))
        //    {
        //        {
        //            var streamContent = new StreamContent(fileStream);
        //            // 添加文件到FormData，指定名称
        //            contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"{fileName}\"" + "");
        //            contentByte.Headers.Remove("Content-Type");
        //            contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png");
        //            content.Add(streamContent, "media", file.Name);
        //        }

        //        // 发送请求
        //        var response = await url.SetBody(content).PostAsStringAsync();
        //        return response;
        //    }
        //}


        //var fileContent = new ByteArrayContent(file, 0, file.Length);
        //MultipartFormDataContent formData = new MultipartFormDataContent();
        //formData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        //formData.Add(fileContent, "media", "1111.pdf");
        //}

        //public string DoPostFile(IFormFile file)
        //{

        //    string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
        //    string startboundary = "--" + boundary;
        //    string endboundary = "--" + boundary + "--";
        //    HttpWebRequest req = GetWebRequest(url, "POST");

        //    req.ContentType = "multipart/form-data;boundary=" + boundary;
        //    System.IO.Stream reqStream = req.GetRequestStream();
        //    //开始结束的换行符不能少，否则是44001,"errmsg":"empty media data, 
        //    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n" + endboundary + "\r\n");
        //    string name = "aaa";
        //    string filename = file.Name;
        //    //结束的两个换行符不能少，否则是44001,"errmsg":"empty media data,
        //    string fileTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"; filelength={2}\r\nContent-Type: {3}\r\n\r\n";


        //    using (var memoryStream = new MemoryStream())
        //    {
        //        file.CopyTo(memoryStream);
        //        byte[] fileBytes = memoryStream.ToArray();
        //        StringBuilder sb = new StringBuilder();
        //        sb.Append(startboundary);
        //        sb.Append("\r\n");
        //        sb.Append(string.Format(fileTemplate, name, filename, fileBytes.Length));
        //        // LogInfo.Error("sb.ToString()=" + sb.ToString());
        //        byte[] Content = Encoding.UTF8.GetBytes(sb.ToString());
        //        //开始标志
        //        reqStream.Write(Content, 0, Content.Length);
        //        //文件内容
        //        reqStream.Write(fileBytes, 0, fileBytes.Length);
        //        //结束标志
        //        reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        //        // LogInfo.Error("endBoundaryBytes=" + endboundary);
        //        reqStream.Close();
        //        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        //        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        //        return GetResponseAsString(rsp, encoding);
        //    }
        //}

        public async Task<string> bb(IFormFile file)

        {
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={Token}&type=file";

            using (var memoryStream = new MemoryStream())
            {
                file.CopyTo(memoryStream);
                var fileByte = memoryStream.ToArray();

                var _httpClient = _httpClientFactory.CreateClient();
                var boundary = DateTime.Now.Ticks.ToString("X");
                _httpClient.DefaultRequestHeaders.Remove("Expect");
                _httpClient.DefaultRequestHeaders.Remove("Connection");
                using (var content = new MultipartFormDataContent(boundary))
                {
                    content.Headers.Remove("Content-Type");
                    content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
                    using (var contentByte = new ByteArrayContent(fileByte))
                    {

                        content.Add(contentByte);
                        contentByte.Headers.Remove("Content-Disposition");
                        contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"{file.FileName}\"" + "");
                        contentByte.Headers.Remove("Content-Type");
                        contentByte.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
                        try
                        {

                            return await _httpClient.PostAsync(url, content).Result.Content.ReadAsStringAsync();
                        }
                        catch (Exception ex)
                        {
                            return ex.Message;
                        }
                    }
                }
            }
        }

        public async Task<dynamic> aa(IFormFile file)
        {
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={Token}&type=file";

            using (var memoryStream = new MemoryStream())
            {
                file.CopyTo(memoryStream);
                var fileByte = memoryStream.ToArray();
                var fileContent = new ByteArrayContent(fileByte, 0, fileByte.Length);
                MultipartFormDataContent formData = new MultipartFormDataContent();
                //formData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                formData.Add(fileContent, "media", file.FileName);

                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                string startboundary = "--" + boundary;
                string endboundary = "--" + boundary + "--";
                string fileTemplate = $@"Content-Disposition: form-data; name='{file.FileName}';filename='{file.FileName}'; filelength={fileByte.Length}\r\nContent-Type: application/octet-stream\r\n\r\n";
                StringBuilder sb = new StringBuilder();
                sb.Append(startboundary);
                sb.Append("\r\n");
                sb.Append(fileTemplate);
                formData.Headers.ContentType = new MediaTypeHeaderValue(sb.ToString());

                var handler = new HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback = delegate { return true; };
                HttpClient client = new HttpClient(handler);

                client.Timeout = TimeSpan.FromSeconds(60);
                client.DefaultRequestHeaders.Add("mimeType", "multipart/form-data");
                var response = await client.PostAsync(url, formData);
                string json = await response.Content.ReadAsStringAsync();
                return json;
            }

        }

        //  public dynamic ccc([FromForm(Name = "file")] IFormFile file, [FromForm(Name = "name")] string name, [FromForm(Name = "age")] string age)
        public dynamic ccc(IFormFile file )
        {
         
            var a = "";
            return file.FileName;
        } 

    public string cc(IFormFile file)
        {
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={Token}&type=file";
            //分割字符串
            var boundary = "----" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => true);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            MemoryStream stream = new MemoryStream();
            file.CopyTo(stream);


            #region 将文件表单写入到内存流

            byte[] filedata = stream.ToArray();
            var filename = file.FileName;
            var temp1 = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\n\r\n",
               boundary, file.FileName, filename);
            byte[] b = Encoding.UTF8.GetBytes(temp1);
            stream.Write(b, 0, b.Length);
            stream.Write(filedata, 0, filedata.Length);

            #endregion
            //结束标记
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(foot_data, 0, foot_data.Length);
            Stream reqStream = request.GetRequestStream();
            stream.Position = 0L;
            //将Form表单生成流写入到请求流中
            stream.CopyTo(reqStream);
            stream.Close();
            reqStream.Close();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();//获取响应
                }
            }
        }

    }
}
